package com.jz.yanshe.adapter;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jz.jd.rest.business.RestProxy;
import com.jz.jd.rest.exception.BusinessException;
import com.jz.jd.rest.response.BaseResponse;
import com.jz.jd.rest.response.ExpressResponse;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.com.feierman.R;

import com.jz.yanshe.ui.ExpressListActivity;
import com.jz.yanshe.ui.RefundActivity;
import com.jz.yanshe.ui.widget.CustomPopWindow;
import com.jz.yanshe.util.ImageLoaderHelper;
import com.jz.yanshe.util.PreferencesHelper;

/**
 * Created by Administrator on 2018/2/28.
 */

public class OrderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public static enum ITEM_TYPE {
        ITEM_HEAD,
        ITEM_BODY,
        ITEM_FOOT
    }

    private LayoutInflater mLayoutInflater;
    private Context mContext;
    private List<OrderWrapper> mList;
    private CustomPopWindow mListPopWindow;
    public RefreshData refreshData;
    private List<ExpressResponse.Express> list = new ArrayList<>();
    MyAdapter adapter;
    View mParent;

    public OrderAdapter(Context context, List list, View mParent) {
        mList = list;
        mContext = context;
        mLayoutInflater = LayoutInflater.from(context);
        this.mParent = mParent;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ITEM_TYPE.ITEM_HEAD.ordinal()) {
            return new HeadHolder(mLayoutInflater.inflate(R.layout.item_order_head, parent, false));
        } else if (viewType == ITEM_TYPE.ITEM_BODY.ordinal()) {
            return new BodyHolder(mLayoutInflater.inflate(R.layout.item_order_body, parent, false));
        } else {
            return new FootHolder(mLayoutInflater.inflate(R.layout.item_order_foot, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        if (holder instanceof HeadHolder) {
            ((HeadHolder) holder).tv_code.setText(mList.get(position).add_time + "      订单号：" + mList.get(position).order_code);
            switch (mList.get(position).order_state) {
                case -2:
                case -3:
                    ((HeadHolder) holder).tv_title.setText("交易取消");
                    break;
                case -1:
                    ((HeadHolder) holder).tv_title.setText("用户取消");
                    break;
                case 1:
                    ((HeadHolder) holder).tv_title.setText("等待买家付款(等待上传凭证)");
                    break;
                case 2:
                    ((HeadHolder) holder).tv_title.setText("等待买家付款(待审核)");
                    break;
                case 3:
                    ((HeadHolder) holder).tv_title.setText("等待买家付款（审核失败）");
                    break;
                case 4:
                    ((HeadHolder) holder).tv_title.setText("等待卖家发货");
                    break;
                case 5:
                    ((HeadHolder) holder).tv_title.setText("已发货");
                    break;
                case 6:
                    ((HeadHolder) holder).tv_title.setText("已收货");
                    break;
                case 7:
                    ((HeadHolder) holder).tv_title.setText("换货中");
                    break;
                case 8:
                    ((HeadHolder) holder).tv_title.setText("换货成功");
                    break;
                case 9:
                    ((HeadHolder) holder).tv_title.setText("换货关闭");
                    break;
                case 10:
                    ((HeadHolder) holder).tv_title.setText("部分发货");
                    break;
                case 11:
                    ((HeadHolder) holder).tv_title.setText("换货成功");
                    break;
                default:
                    ((HeadHolder) holder).tv_title.setText("交易关闭");
                    break;
            }

        } else if (holder instanceof BodyHolder) {
            ImageLoaderHelper.getInstance().GlideImageLoader(mContext, mList.get(position).goods_icon, ((BodyHolder) holder).img_goods);
            ((BodyHolder) holder).tv_goods_name.setText(mList.get(position).goods_name);
            ((BodyHolder) holder).tv_goods_num.setText("x " + mList.get(position).goods_num);
            ((BodyHolder) holder).tv_goods_size.setText(mList.get(position).style_color + "     " + mList.get(position).style_size + "码");
            ((BodyHolder) holder).tv_price.setText("¥ " + mList.get(position).actual_price);
        } else if (holder instanceof FootHolder) {
            ((FootHolder) holder).tv_total_num.setText("共" + mList.get(position).goods_total_num + "件商品");
            ((FootHolder) holder).tv_total_price.setText("¥ " + mList.get(position).total_price);
            switch (mList.get(position).order_state) {
                case 1:
                    ((FootHolder) holder).bottom.setVisibility(View.VISIBLE);
                    if (mList.get(position).pay_type == 1) {
                        ((FootHolder) holder).tv1.setText("付款");
                    } else {
                        ((FootHolder) holder).tv1.setText("上传结款凭据");
                        ((FootHolder) holder).tv1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                refreshData.openGallery(mList.get(position).order_id, mList.get(position).pay_price);
                            }
                        });
                    }
                    ((FootHolder) holder).tv2.setVisibility(View.VISIBLE);
                    ((FootHolder) holder).tv2.setText("取消订单");
                    ((FootHolder) holder).tv2.setTextColor(mContext.getResources().getColor(R.color.lightBlack));
                    ((FootHolder) holder).tv2.setBackgroundResource(R.drawable.item_bg_grey);
                    ((FootHolder) holder).tv2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            cancelOrder(mList.get(position).order_id);
                        }
                    });
                    break;
                case 3:
                    ((FootHolder) holder).bottom.setVisibility(View.VISIBLE);
                    if (mList.get(position).pay_type == 1) {
                        ((FootHolder) holder).tv1.setText("付款");
                    } else {
                        ((FootHolder) holder).tv1.setText("上传结款凭据");
                        ((FootHolder) holder).tv1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                refreshData.openGallery(mList.get(position).order_id, mList.get(position).pay_price);
                            }
                        });
                    }
                    ((FootHolder) holder).tv2.setVisibility(View.INVISIBLE);
//                    ((FootHolder) holder).tv2.setText("取消订单");
//                    ((FootHolder) holder).tv2.setTextColor(mContext.getResources().getColor(R.color.lightBlack));
//                    ((FootHolder) holder).tv2.setBackgroundResource(R.drawable.item_bg_grey);
//                    ((FootHolder) holder).tv2.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            cancelOrder(mList.get(position).order_id);
//                        }
//                    });
                    break;
                case 2:
                    ((FootHolder) holder).bottom.setVisibility(View.VISIBLE);
                    if (mList.get(position).pay_type == 1) {
                        ((FootHolder) holder).tv1.setText("付款");
                    } else {
                        ((FootHolder) holder).tv1.setText("上传结款凭据");
                        ((FootHolder) holder).tv1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Toast.makeText(mContext, "正在审核中", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                    ((FootHolder) holder).tv2.setVisibility(View.INVISIBLE);
//                    ((FootHolder) holder).tv2.setText("取消订单");
//                    ((FootHolder) holder).tv2.setTextColor(mContext.getResources().getColor(R.color.lightBlack));
//                    ((FootHolder) holder).tv2.setBackgroundResource(R.drawable.item_bg_grey);
//                    ((FootHolder) holder).tv2.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            cancelOrder(mList.get(position).order_id);
//                        }
//                    });
                    break;
                case 4:
                    ((FootHolder) holder).bottom.setVisibility(View.VISIBLE);
                    ((FootHolder) holder).tv1.setText("提醒发货");
                    ((FootHolder) holder).tv1.setTextColor(mContext.getResources().getColor(R.color.lightBlack));
                    ((FootHolder) holder).tv1.setBackgroundResource(R.drawable.item_bg_grey);
                    ((FootHolder) holder).tv1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(mContext, "已提醒卖家发货", Toast.LENGTH_SHORT).show();
                        }
                    });
//                    ((FootHolder) holder).tv2.setVisibility(View.VISIBLE);
//                    ((FootHolder) holder).tv2.setText("取消订单");
//                    ((FootHolder) holder).tv2.setTextColor(mContext.getResources().getColor(R.color.lightBlack));
//                    ((FootHolder) holder).tv2.setBackgroundResource(R.drawable.item_bg_grey);
//                    ((FootHolder) holder).tv2.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            cancelOrder(mList.get(position).order_id);
//                        }
//                    });
                    break;
                case 10:
                    ((FootHolder) holder).bottom.setVisibility(View.VISIBLE);
                    ((FootHolder) holder).tv1.setText("查看物流");
                    ((FootHolder) holder).tv1.setTextColor(mContext.getResources().getColor(R.color.lightBlack));
                    ((FootHolder) holder).tv1.setBackgroundResource(R.drawable.item_bg_grey);
                    ((FootHolder) holder).tv1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                            showPopListView(((FootHolder) holder).tv2, mList.get(position).order_id);
                            Intent mIntent = new Intent(mContext, ExpressListActivity.class);
                            mIntent.putExtra("orderid", mList.get(position).order_id);
                            mContext.startActivity(mIntent);
                        }
                    });
                    break;
                case 5:
                    ((FootHolder) holder).bottom.setVisibility(View.VISIBLE);
                    ((FootHolder) holder).tv1.setText("确认收货");
                    ((FootHolder) holder).tv1.setTextColor(mContext.getResources().getColor(R.color.commonRed));
                    ((FootHolder) holder).tv1.setBackgroundResource(R.drawable.item_bg_red);
                    ((FootHolder) holder).tv1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialogShow(mList.get(position).order_id);
                        }
                    });

                    ((FootHolder) holder).tv2.setVisibility(View.VISIBLE);
                    ((FootHolder) holder).tv2.setText("查看物流");
                    ((FootHolder) holder).tv2.setTextColor(mContext.getResources().getColor(R.color.lightBlack));
                    ((FootHolder) holder).tv2.setBackgroundResource(R.drawable.item_bg_grey);
                    ((FootHolder) holder).tv2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                            showPopListView(((FootHolder) holder).tv2, mList.get(position).order_id);
                            Intent mIntent = new Intent(mContext, ExpressListActivity.class);
                            mIntent.putExtra("orderid", mList.get(position).order_id);
                            mContext.startActivity(mIntent);
                        }
                    });
//                    ((FootHolder) holder).tv3.setVisibility(View.VISIBLE);
//                    ((FootHolder) holder).tv3.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//
//                            dialogShowRefund(mList.get(position).order_id);
//                        }
//                    });
                    break;
                case 6:
//                    ((FootHolder) holder).tv1.setText("查看物流");
//                    ((FootHolder) holder).tv1.setTextColor(mContext.getResources().getColor(R.color.lightBlack));
//                    ((FootHolder) holder).tv1.setBackgroundResource(R.drawable.item_bg_grey);
//                    ((FootHolder) holder).tv1.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            showPopListView(((FootHolder) holder).tv1, mList.get(position).order_id);
//                        }
//                    });
                    ((FootHolder) holder).bottom.setVisibility(View.VISIBLE);
                    ((FootHolder) holder).tv1.setText("换货");
                    ((FootHolder) holder).tv1.setTextColor(mContext.getResources().getColor(R.color.lightBlack));
                    ((FootHolder) holder).tv1.setBackgroundResource(R.drawable.item_bg_grey);
                    ((FootHolder) holder).tv1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", mList.get(position).order_id);
                            Intent mIntent = new Intent(mContext, RefundActivity.class);
                            mIntent.putExtras(bundle);
                            mContext.startActivity(mIntent);
                        }
                    });
                    break;
                default:
                    ((FootHolder) holder).bottom.setVisibility(View.GONE);
                    break;
            }

        }
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    @Override
    public int getItemViewType(int position) {
        return mList.get(position).item_type;
    }

    class HeadHolder extends RecyclerView.ViewHolder {
        TextView tv_title, tv_code;

        public HeadHolder(View itemView) {
            super(itemView);
            tv_title = itemView.findViewById(R.id.tv_title);
            tv_code = itemView.findViewById(R.id.tv_code);
        }
    }

    class BodyHolder extends RecyclerView.ViewHolder {
        ImageView img_goods;
        TextView tv_goods_size, tv_goods_name, tv_goods_num, tv_price, tv_price_now;

        public BodyHolder(View itemView) {
            super(itemView);
            img_goods = itemView.findViewById(R.id.img_goods);
            tv_goods_size = itemView.findViewById(R.id.tv_goods_size);
            tv_goods_name = itemView.findViewById(R.id.tv_goods_name);
            tv_goods_num = itemView.findViewById(R.id.tv_goods_num);
            tv_price = itemView.findViewById(R.id.tv_price);
            tv_price_now = itemView.findViewById(R.id.tv_price_now);
        }
    }

    class FootHolder extends RecyclerView.ViewHolder {
        TextView tv_total_num, tv_total_price, tv1, tv2, tv3;
        RelativeLayout bottom;

        public FootHolder(View itemView) {
            super(itemView);
            tv_total_num = itemView.findViewById(R.id.tv_total_num);
            tv_total_price = itemView.findViewById(R.id.tv_total_price);
            tv1 = itemView.findViewById(R.id.tv1);
            tv2 = itemView.findViewById(R.id.tv2);
            tv3 = itemView.findViewById(R.id.tv3);
            bottom = itemView.findViewById(R.id.bottom);
        }
    }

    private void showPopListView(View view, String order_id) {
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.pop_list, null);
        RecyclerView recyclerView = contentView.findViewById(R.id.recyclerView);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        getExpressInfo(order_id);
        //创建并显示popWindow
        mListPopWindow = new CustomPopWindow.PopupWindowBuilder(mContext)
                .setView(contentView)
                .size(0, 0) // 显示大小
                .create()
                .showAtLocation(mParent, Gravity.CENTER, 0, 0);
    }


    private void confirmOrder(String order_id) {
        RestProxy.getInstance().confirmOrder(PreferencesHelper.getInstance().getString(mContext, "token"), order_id, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                refreshData.refreshData();
            }

            @Override
            public void onError(Throwable e) {
//                toLogin(((BusinessException)e).errorCode);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void getExpressInfo(String order_id) {
        RestProxy.getInstance().getExpressInfo(PreferencesHelper.getInstance().getString(mContext, "token"), order_id, new Observer<ExpressResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ExpressResponse expressResponse) {
                list.clear();
                list.addAll(expressResponse.list);
                OrderAdapter.this.adapter.notifyDataSetChanged();
            }


            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    public interface RefreshData {

        void refreshData();

        void openGallery(String order_id, String pay_price);
    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {

        @Override
        public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            MyAdapter.Holder myHolder = new MyAdapter.Holder(LayoutInflater.from(mContext).inflate(R.layout.item_express, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(MyAdapter.Holder holder, final int position) {
            holder.tv_express_no.setText(list.get(position).express_code);
            holder.tv_express_name.setText(list.get(position).express_name);
        }


        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_express_no, tv_express_name;

            public Holder(View itemView) {
                super(itemView);
                tv_express_no = (TextView) itemView.findViewById(R.id.tv_express_no);
                tv_express_name = (TextView) itemView.findViewById(R.id.tv_express_name);
            }
        }
    }


    private void dialogShow(final String order_id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_confirm_goods, null);
        Button btn_sure = (Button) v.findViewById(R.id.dialog_btn_sure);
        Button btn_cancel = (Button) v.findViewById(R.id.dialog_btn_cancel);
        //builer.setView(v);//这里如果使用builer.setView(v)，自定义布局只会覆盖title和button之间的那部分
        final Dialog dialog = builder.create();
        dialog.show();
        dialog.getWindow().setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        //dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                confirmOrder(order_id);
                dialog.dismiss();
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }


//    private void dialogShowRefund(final String order_id) {
//        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
//        LayoutInflater inflater = LayoutInflater.from(mContext);
//        View v = inflater.inflate(R.layout.dialog_refund, null);
//        Button btn_sure = (Button) v.findViewById(R.id.dialog_btn_sure);
//        final EditText tv_express_name = v.findViewById(R.id.tv_express_name);
//        final EditText tv_express_no = v.findViewById(R.id.tv_express_no);
//        //builer.setView(v);//这里如果使用builer.setView(v)，自定义布局只会覆盖title和button之间的那部分
//        final Dialog dialog = builder.create();
//        dialog.show();
//        dialog.getWindow().setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
//        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
//        //dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
//        btn_sure.setOnClickListener(new View.OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                refund(order_id, tv_express_no.getText().toString().trim(), tv_express_name.getText().toString().trim());
//                dialog.dismiss();
//            }
//        });
//    }


//    private void refund(String order_id, String express_code, String express_name) {
//        RestProxy.getInstance().refund(PreferencesHelper.getInstance().getString(mContext, "token"), order_id, express_code, express_name, new Observer<BaseResponse>() {
//            @Override
//            public void onSubscribe(Disposable d) {
//
//            }
//
//            @Override
//            public void onNext(BaseResponse baseResponse) {
//                refreshData.refreshData();
//                Toast.makeText(mContext, baseResponse.message, Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                if (e instanceof BusinessException) {
//                    Toast.makeText(mContext, ((BusinessException) e).errorDescription, Toast.LENGTH_SHORT).show();
//                }
//            }
//
//            @Override
//            public void onComplete() {
//
//            }
//        });
//    }

    private void cancelOrder(String order_id) {
        RestProxy.getInstance().cancelOrder(PreferencesHelper.getInstance().getString(mContext, "token"), order_id, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                refreshData.refreshData();
                Toast.makeText(mContext, baseResponse.message, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable e) {
                if (e instanceof BusinessException) {
                    Toast.makeText(mContext, ((BusinessException) e).errorDescription, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onComplete() {

            }
        });
    }

}
